// Add tracks.
(function () {
    var tracksLayer = new Kinetic.Layer({
        "name": "tracks"
    });
    State.stage.add(tracksLayer);

    // Wire reset button to reset display on all tracks.
    Events.reset.on(function () {
        $.each(State.tracks, function (index, track) {
            track.reset();
        });
    });

    $.each(Data.routes, function (index, routeData) {
        var from = State.cities[routeData.from];
        var to = State.cities[routeData.to];

        if (from === undefined) {
            throw ("Attempt to create route from unknown city (" + routeData.from + ").");
        }
        if (to === undefined) {
            throw ("Attempt to create route to unknown city (" + routeData.to + ").");
        }

        $.each(routeData.tracks, function (index, trackData) {
            var track = new UI.Track(State.scorer, from, to, trackData, tracksLayer);
            State.tracks.push(track);

            track.events.clicked.on(function () {
                Events.track.clicked.fire(track);
            });
            track.events.tapped.on(function () {
                Events.track.tapped.fire(track);
            });
            track.events.entered.on(function () {
                Events.track.entered.fire(track);
            });
            track.events.exited.on(function () {
                Events.track.exited.fire(track);
            });
        });
    });
}());
